package models

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"yixiang.co/yshop/common/untils"
)

type YshopStoreCategory struct {
	Id       int64                `json:"id"`
	CateName string               `json:"cateName" valid:"Required;"`
	Pid      int64                `json:"pid"`
	Sort     int                  `json:"sort"`
	Pic      string               `json:"pic"`
	IsShow   int8                 `json:"isShow"`
	Children []YshopStoreCategory `orm:"-" json:"children"`
	Label    string               `  orm:"-" json:"label"`
	BaseModel
}

func init() {
	orm.RegisterModel(new(YshopStoreCategory))
}

func GetAllCates(name string, enabled int8) []YshopStoreCategory {
	var data []YshopStoreCategory
	o := orm.NewOrm()
	qs := o.QueryTable("yshop_store_category").Filter("is_del", 0).OrderBy("sort")
	if name != "" {
		qs = qs.Filter("name", name)
	}
	if enabled > -1 {
		qs = qs.Filter("is_show", enabled)
	}
	qs.All(&data)
	return RecursionCateList(data, 0)
}

//递归函数
func RecursionCateList(data []YshopStoreCategory, pid int64) []YshopStoreCategory {
	var listTree = make([]YshopStoreCategory, 0)
	for _, value := range data {
		value.Label = value.CateName
		if value.Pid == pid {
			value.Children = RecursionCateList(data, value.Id)
			listTree = append(listTree, value)
		}
	}
	return listTree
}

func AddCate(m *YshopStoreCategory) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

func UpdateByCate(m *YshopStoreCategory) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m)
	return
}

func DelByCate(ids []int64) (err error) {
	str := untils.ReturnQ(len(ids))
	logs.Info(str)
	o := orm.NewOrm()
	_, err = o.Raw("UPDATE yshop_store_category SET is_del = ? WHERE id in("+str+")", 1, ids).Exec()
	return
}

//返回一定格式的分类数据
func GetProductCate() []map[string]interface{} {
	var (
		retList []map[string]interface{}
	)

	list := GetAllCates("", 1)

	for _, value := range list {
		var mapData = make(map[string]interface{})
		mapData["value"] = value.Id
		mapData["label"] = "|----" + value.CateName
		if value.Pid == 0 {
			mapData["disabled"] = 0
		} else {
			mapData["disabled"] = 1
		}
		retList = append(retList, mapData)
		if value.Children != nil && len(value.Children) > 0 {
			for _, value2 := range value.Children {
				var mapData2 = make(map[string]interface{})
				mapData2["value"] = value2.Id
				mapData2["label"] = "|----|----" + value2.CateName
				if value2.Pid == 0 {
					mapData2["disabled"] = 0
				} else {
					mapData2["disabled"] = 1
				}
				retList = append(retList, mapData2)
			}
		}

	}

	return retList
}
